import { _decorator, Component, instantiate, Node, NodePool, Prefab, resources } from 'cc';
import { Dictionary } from './Dictionary';
const { ccclass, property } = _decorator;

@ccclass('PoolMgr')
export class PoolMgr {
    
    nodePoolsDic:Dictionary<string,NodePool>=new Dictionary();
    poolPrefabDic:Dictionary<string,Prefab>=new Dictionary();//key：池的名字，value：对应预制体

    static ins:PoolMgr=null;
   
    static getIns(){
        if (PoolMgr.ins==null) {
            PoolMgr.ins=new PoolMgr();
        }
        return PoolMgr.ins;
    }

    initAllPool(poolName, prefab, count) {//如果初始化成功返回promise对象
        return new Promise((resolve, reject) => {
            if (this.nodePoolsDic.containsKey(poolName) == false) {
                this.nodePoolsDic.set(poolName, new NodePool())
                this.poolPrefabDic.set(poolName, prefab)
                for (let i = 0; i < count; i++) {
                    let pre = instantiate(prefab);
                    this.nodePoolsDic.get(poolName).put(pre)
                    if (i + 1 == count) {
                        resolve(true);
                    }
                }
            }
        })

    }

    poolGet(_poolName: string) {
        let res = null;
        res = this.nodePoolsDic.get(_poolName).get();
        while (res==null) {
           let pre=instantiate(this.poolPrefabDic.get(_poolName));
           this.nodePoolsDic.get(_poolName).put(pre)
           res = this.nodePoolsDic.get(_poolName).get();
        }

        return res;
    }

    poolPut(_poolName, _node) {
        this.nodePoolsDic.get(_poolName).put(_node)
    }


}


